/**
 * @description 文档-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 查询产品下的所有页面与功能
  */
  queryNodeTree (action) {
    // 解析数据
    return this.query(action).then(async res => {
      let product = res.data || {}
      product.children = Array.isArray(product.children) ? product.children : []
      if (product && product.id) {
        // 查询所有的页面数据
        let pages = await this.$router.getControllInstance({name: 'page'}).queryTreeSub({}, {
          action: {},
          query: {},
          params: {
            id: '',
            productId: product.id
          },
          excute: {
            operators: [
              {field: 'productId', operator: 'EQUAL'}
            ],
            sort: [
              {field: 'createTime', by: 'desc'},
              {field: 'order', by: 'desc'}
            ],
            treeLevel: 99
          }
        })
        pages = (pages.data || {}).list
        pages = Array.isArray(pages) ? pages : []
        product.children = pages
        let defers = []
        pages.forEach(page => {
          // 查询所有的功能数据
          let defer = this.$router.getControllInstance({path: '/tigerlair/func'}).queryTreeSub({}, {
            action: {},
            query: {},
            params: {
              id: '',
              pageId: page.id
            },
            excute: {
              operators: [
                {field: 'pageId', operator: 'EQUAL'}
              ],
              sort: [
                {field: 'createTime', by: 'desc'},
                {field: 'order', by: 'desc'}
              ],
              treeLevel: 99
            }
          }).then(funcs => {
            funcs = (funcs.data || {}).list
            funcs = Array.isArray(funcs) ? funcs : []
            page.children = Array.isArray(page.children) ? page.children : []
            page.children = page.children.concat(funcs)
          })
          defers.push(defer)
        })
        await Promise.allSettled(defers)
      }
      return {data: {list: [product]}, success: 1}
    })
  }
}

module.exports = Controller